package com.plantuml.server.service;

import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Service
public class PlantUmlService {

    /**
     * 生成PlantUML图片
     * @param umlCode PlantUML代码
     * @return 图片字节数组
     * @throws IOException 如果生成失败
     */
    public byte[] generateImage(String umlCode) throws IOException {
        if (umlCode == null || umlCode.trim().isEmpty()) {
            throw new IllegalArgumentException("PlantUML code cannot be null or empty");
        }

        // 确保代码以@startuml开头
        if (!umlCode.trim().startsWith("@startuml")) {
            umlCode = "@startuml\n" + umlCode;
        }

        // 确保代码以@enduml结尾
        if (!umlCode.trim().endsWith("@enduml")) {
            umlCode = umlCode + "\n@enduml";
        }

        SourceStringReader reader = new SourceStringReader(umlCode);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        
        reader.generateImage(outputStream, new FileFormatOption(FileFormat.PNG));
        
        return outputStream.toByteArray();
    }

    /**
     * 从URL编码的字符串生成PlantUML图片
     * @param encoded 编码的PlantUML代码
     * @return 图片字节数组
     * @throws IOException 如果生成失败
     */
    public byte[] generateImageFromEncoded(String encoded) throws IOException {
        if (encoded == null || encoded.trim().isEmpty()) {
            throw new IllegalArgumentException("Encoded PlantUML code cannot be null or empty");
        }

        // URL解码
        String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
        
        return generateImage(decoded);
    }
} 